//
//  Product_Checkout4View.m
//  iFlower
//
//  Created by khanh nguyen on 7/26/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "Product_Checkout4View.h"
#import "RootViewController.h"
#import "Request.h"
#import "iFlowerAppDelegate.h"
#import "Address.h"
#import "Country.h"
#import "State.h"
#import "Payment.h"
#import "Basket.h"
#import "User.h"
#import "PayPal.h"
#import "MEPAmounts.h"
#import "MEPAddress.h"
#import "PayPalMEPPayment.h"
#import "OrderResultsViewController.h"
#import "MyAccountView.h"
#import "LoginView.h"

@implementation Product_Checkout4View

@synthesize Title;
@synthesize fname;
@synthesize lname;
@synthesize phone;
@synthesize email;
@synthesize address;
@synthesize city;
@synthesize country;
@synthesize state;
@synthesize post_code;
@synthesize Fname2;
@synthesize Lname2;
@synthesize Address2;
@synthesize City2;
@synthesize State2;
@synthesize Country2;
@synthesize Post_code2;
@synthesize paymentMethod;
@synthesize btnRegister;

#pragma mark UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
	if(buttonIndex!=-1)
	{
		[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://www.paypal.com"]];
	}
}

-(IBAction)buttonBack:(id)sender
{
	[self.navigationController popViewControllerAnimated:YES];
}
-(IBAction)button_Submit:(id)sender
{
	
	//[[[[UIAlertView alloc] initWithTitle:@"Payment Process" message:@"You will redirect into safari for payment process" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK",nil] autorelease] show];
}
-(IBAction)buttonMenu:(id)sender
{
	[self.navigationController popToRootViewControllerAnimated:YES];
}
-(IBAction) buttonMyAccount
{
	if ([[iFlowerAppDelegate shareDelegate] logined]) {
		MyAccountView * account = [[MyAccountView alloc] initWithNibName:@"MyAccountView" bundle:nil];
		[self.navigationController pushViewController:account animated:YES];
		[account release];
	}
	else {
		LoginView * login = [[LoginView alloc] initWithNibName:@"LoginView" bundle:nil];
		[self.navigationController pushViewController:login animated:YES];
		[login release];		
	}
	
}
#pragma mark -
#pragma mark View lifecycle
- (void) viewWillAppear:(BOOL)animated
{
	[super viewWillAppear:animated];
	if([[iFlowerAppDelegate shareDelegate] logined])
	{
		self.btnRegister.enabled = NO;
	}else {
		self.btnRegister.enabled = YES;
	}
}


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	User* user = [[iFlowerAppDelegate shareDelegate] user];
	self.paymentMethod.text = [[[iFlowerAppDelegate shareDelegate] payment] paymentMethod];
	Address* shipAddress = [[[iFlowerAppDelegate shareDelegate] payment] shipAddress];
	self.Title.text = user.tittle;
	self.fname.text = user.firstName;
	self.email.text = user.email;
	self.phone.text = user.phone;
	self.lname.text = user.lastName;
	self.address.text = user.billingAddress;
	self.city.text = user.billingCity;
	self.state.text = user.billingState;
	self.country.text = user.billingCountry;
	self.post_code.text = user.billingZipcode;
	self.Fname2.text = shipAddress.firstName;
	self.Lname2.text = shipAddress.lastName;
	self.Address2.text = [NSString stringWithFormat:@"%@ %@",shipAddress.addressLine1,shipAddress.addressLine2];
	self.City2.text = shipAddress.city;
	self.Country2.text = shipAddress.country;
	self.State2.text = shipAddress.state;
	self.Post_code2.text = shipAddress.zipCode;
	
	//We need to figure out the PayPal Library payment type. Sets whether the payment type is hard goods or service
	UIButton *button = [[PayPal getInstance] getPayButton:self buttonType:BUTTON_118x24
																					  startCheckOut:@selector(payWithPayPal) PaymentType:HARD_GOODS
																						   withLeft:200 withTop:44]; 
	[self.view addSubview:button];
	
}


/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}


- (void)dealloc {
	[paymentMethod release];
	[phone release];
	[email release];
	[lname release];
	[fname release];
	[address release];
	[Address2 release];
	[City2 release];
	[Title release];
	[city release];
	[country release];
	[state release];
	[post_code release];
	[Post_code2 release];
	[Fname2 release];
	[Lname2 release];
	[State2 release];
	[country release];
    [super dealloc];
}
- (void) contentLoaded:(NSNotification*) notification
{
	[[NSNotificationCenter defaultCenter] removeObserver:self];
	NSLog(@"content loaded");
	[[iFlowerAppDelegate shareDelegate] refreshBasket];

	[[iFlowerAppDelegate shareDelegate] hideLoadingView];
}
- (void) contentFailed:(NSNotification*) notification
{
	[[NSNotificationCenter defaultCenter] removeObserver:self];
	NSLog(@"content failed");
	[[iFlowerAppDelegate shareDelegate] refreshBasket];

	[[iFlowerAppDelegate shareDelegate] hideLoadingView];
}

#pragma mark -
#pragma mark Paypal Process
-(void)payWithPayPal {
	//Once the user clicks the 'Pay with PayPal' button:
	
	//Keep a local variable so we can easily access the PayPal object
	PayPal *ppMEP = [PayPal getInstance];
	
	//If we will be delivering, call the 'EnableShipping' method so that the user will be prompted to choose an address
	[ppMEP DisableShipping];
	
	//Calling 'enableDynamicAmountUpdate' allows us to modify the shipping fee after the user chooses a shipping address.
	//The method that gets called is 'AdjustAmounts', which we have below
	//[ppMEP enableDynamicAmountUpdate];
	
	//If the payment has a fee and the user is allowed to decide who pays it, defaults the fee to be "recipient pays fee"
	[ppMEP feePaidByReceiver];
	
	//This lets us default the user's email address. If we already know the user's email, we can automatically enter it into the username
	//field on the login page. If the user has previously logged in a a username is saved, that will be displayed instead of whatever
	//is passed into this method.
	[ppMEP SetSenderEmailorPhone:[[[iFlowerAppDelegate shareDelegate] user] email]];
	
	//Defines our payment object
	PayPalMEPPayment *payment = [[PayPalMEPPayment alloc] init];
	
	//Sets the payment currency
	payment.paymentCurrency = @"GBP";
	
	//Sets the payment amount. We make sure it only has 2 decimal places
	payment.paymentAmount = [NSString stringWithFormat:@"%.2f",[[[iFlowerAppDelegate shareDelegate] basket] finalBasketPrice]];
	
	//Sets the item description that will be displayed to the user to the description we defined earlier
	payment.itemDesc = @"Payment for flowersonline24.com";
	
	//Sets the recipient for the payment -- this would be the PayPal account we want the money sent to 
	payment.recipient = @"info@flowersonline24.com";//@"recipient@paypal.com";//@"info@flowersonline24.com";
	
	//Sets the tax amount. We can modify this after the user picks an address through the 'AdjustAmounts' method,
	//because we called the 'enableDynamicAmountUpdate' method
	payment.taxAmount = [NSString stringWithFormat:@"%.2f",0.0];
	
	//Sets the shipping amount. We can modify this after the user picks an address through the 'AdjustAmounts' method.
	payment.shippingAmount = @"0.0";//[NSString stringWithFormat:@"%.2f",[[[iFlowerAppDelegate shareDelegate] basket] shippingFee]];
	
	//Sets the merchant name that will be displayed to the user at the top of the PayPal Library window
	payment.merchantName = @"Elisana Ltd.";
	
	//Starts the checkout
	[ppMEP Checkout:payment];
	[payment release];
}

-(void)paymentSuccess:(NSString*)transactionID
{
	
	OrderResultsViewController *orderResultsViewController = [[OrderResultsViewController alloc] initWithNibName:@"OrderResults"
																										  bundle:nil];
	//Shows the user appropriate text based on whether it was a delivery or not.
	orderResultsViewController.forDelivery = YES;
	[[Request sharedRequest] saveOrder:[[iFlowerAppDelegate shareDelegate]order]];
	//Shows the user the transactionID that we got from the PayPal Library
	[[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(contentLoaded:) name: @"ContentLoaded" object: nil];
	[[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(contentFailed:) name: @"ContentFailed" object: nil];
	[[iFlowerAppDelegate shareDelegate] showLoadingView];
	orderResultsViewController.transactionID = transactionID;
	[self.navigationController pushViewController:orderResultsViewController animated:NO];	
	[orderResultsViewController release];
}
-(void)paymentCanceled
{
	//If the user canceled the Payment, show a UIAlertView
	UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Order canceled" 
													message:@"You canceled your order. Touch \"Pay with PayPal\" to try again." 
												   delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
	[alert show];
	[alert release];
}
-(void)paymentFailed:(PAYPAL_FAILURE)errorType
{
	NSLog(@"payment error: %d",errorType);
	//If the payment failed, show the user an error message. We could use the 'errorType' value to let the user know more details about the error
	UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Order failed" 
													message:@"Your order failed. Touch \"Pay with PayPal\" to try again." 
												   delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
	[alert show];
	[alert release];
}

@end
